package vip.aster.framework.security.exception;

import cn.hutool.json.JSONUtil;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import vip.aster.common.utils.HttpContextUtils;
import vip.aster.common.utils.ResultInfo;

import java.io.IOException;

/**
 * SecurityAuthenticationEntryPoint
 *
 * @author Aster
 * @since 2023/11/27 10:18
 */
public class SecurityAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        response.setContentType("application/json; charset=utf-8");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Origin", HttpContextUtils.getOrigin());

        response.getWriter().print(JSONUtil.toJsonStr(ResultInfo.unauthorized()));
    }
}
